import React, { useEffect, useRef, useState } from 'react';
import '../styles/TimelineChart.css';

const TimelineChart = ({ data, height = 350, isFiveDay = false }) => {
  const canvasRef = useRef(null);
  const [mousePosition, setMousePosition] = useState(null);
  const chartInfoRef = useRef({
    padding: { top: 20, right: 60, bottom: 60, left: 60 },
    priceChartHeight: 0,
    volumeChartHeight: 0,
    volumeChartTop: 0,
    chartWidth: 0,
    minPrice: 0,
    maxPrice: 0,
    priceRange: 0,
    maxVolume: 0,
    preClose: 0
  });

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    const width = canvas.width;
    const canvasHeight = canvas.height;

    // 清除画布
    ctx.clearRect(0, 0, width, canvasHeight);

    // 绘制分时图
    drawTimelineChart(ctx, width, canvasHeight);

  }, [data, height, mousePosition]);

  // 处理鼠标移动
  const handleMouseMove = (e) => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const rect = canvas.getBoundingClientRect();
    const x = (e.clientX - rect.left) * (canvas.width / rect.width);
    const y = (e.clientY - rect.top) * (canvas.height / rect.height);
    
    setMousePosition({ x, y });
  };

  // 处理鼠标离开
  const handleMouseLeave = () => {
    setMousePosition(null);
  };

  // 绘制分时图
  const drawTimelineChart = (ctx, width, height) => {
    // 兼容两种数据结构：
    // 1. {time: [], price: [], volume: []}
    // 2. {data: [{time, price, vol}]}
    if (!data) {
      console.warn('Timeline chart requires data');
      return;
    }

    let timeArray, priceArray, volumeArray;
    if (Array.isArray(data.data)) {
      // 处理第二种数据结构
      timeArray = data.data.map(item => item.time);
      priceArray = data.data.map(item => item.price);
      volumeArray = data.data.map(item => item.vol);
    } else {
      // 处理第一种数据结构
      timeArray = data.time || [];
      priceArray = data.price || [];
      volumeArray = data.volume || [];
    }
    // console.log('arryay is:',timeArray, priceArray, volumeArray)

    if (priceArray.length === 0) {
      console.warn('Timeline chart requires price data');
      return;
    }

    const padding = { top: 20, right: 60, bottom: 60, left: 60 };
    const chartWidth = width - padding.left - padding.right;
    const priceChartHeight = height * 0.7 - padding.top - padding.bottom;
    const volumeChartHeight = height * 0.3 - 20;
    const volumeChartTop = height - volumeChartHeight - padding.bottom;

    // 找出价格的最大值和最小值
    const preClose = data.preClose || priceArray[0]; // 昨收价
    const maxPrice = Math.max(...priceArray) * 1.002;
    const minPrice = Math.min(...priceArray) * 0.998;
    const priceRange = maxPrice - minPrice;
    
    // 保存图表信息到ref中，供十字线使用
    chartInfoRef.current = {
      padding,
      priceChartHeight,
      volumeChartHeight,
      volumeChartTop,
      chartWidth,
      minPrice,
      maxPrice,
      priceRange,
      maxVolume: Math.max(...volumeArray),
      preClose
    };

    // 计算涨跌幅
    const maxPercent = ((maxPrice - preClose) / preClose * 100).toFixed(2);
    const minPercent = ((minPrice - preClose) / preClose * 100).toFixed(2);

    // 找出成交量的最大值
    const maxVolume = volumeArray.length > 0 ? Math.max(...volumeArray) : 0;

    // 绘制网格和坐标轴 - 根据是否是5日分时调整网格线数量
    const daysCount = isFiveDay ? 5 : 1; // 5日分时显示5天，普通分时显示1天
    drawGrid(ctx, padding.left, padding.top, chartWidth, priceChartHeight, 4, daysCount); // 价格区域4条水平线
    drawGrid(ctx, padding.left, volumeChartTop, chartWidth, volumeChartHeight, 0, daysCount); // 成交量区域按天数划分

    // 绘制昨收价参考线
    drawPreCloseLine(ctx, padding.left, padding.top, chartWidth, priceChartHeight, preClose, minPrice, priceRange);

    // 绘制Y轴价格标签
    drawYAxisLabels(ctx, padding.left, padding.top, priceChartHeight, minPrice, maxPrice, 5);
    
    // 绘制右侧涨跌幅标签
    drawPercentLabels(ctx, padding.left + chartWidth, padding.top, priceChartHeight, minPercent, maxPercent, 5);

    // 绘制Y轴成交量标签
    if (volumeArray.length > 0) {
      drawVolumeYAxisLabels(ctx, padding.left, volumeChartTop, volumeChartHeight, maxVolume, 3);
    }

    // 绘制X轴时间标签
    drawXAxisLabels(ctx, padding.left, height - padding.bottom, chartWidth, timeArray);

    // 绘制价格线
    drawPriceLine(ctx, padding.left, padding.top, chartWidth, priceChartHeight, priceArray, minPrice, priceRange);

    // 绘制成交均价线
    if (data.avgPrice && data.avgPrice.length > 0) {
      drawAverageLine(ctx, padding.left, padding.top, chartWidth, priceChartHeight, data.avgPrice, minPrice, priceRange, '#ffb100');
    }

    // 绘制成交量柱状图
    if (volumeArray.length > 0) {
      drawVolumeChart(ctx, padding.left, volumeChartTop, chartWidth, volumeChartHeight, volumeArray, maxVolume, priceArray);
    }
    
    // 不再绘制图例
    // drawLegend(ctx, width - padding.right - 150, padding.top + 10);
    
    // 绘制十字线和数据标签
    if (mousePosition) {
      drawCrosshair(ctx, width, height);
    }
  };

  // 绘制网格
  const drawGrid = (ctx, x, y, width, height, hLines, vLines) => {
    ctx.beginPath();
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
    ctx.lineWidth = 0.5;

    // 水平线
    if (hLines > 0) {
      const step = height / hLines;
      for (let i = 0; i <= hLines; i++) {
        const lineY = y + i * step;
        ctx.moveTo(x, lineY);
        ctx.lineTo(x + width, lineY);
      }
    }

    // 垂直线
    if (vLines > 0) {
      const step = width / vLines;
      for (let i = 0; i <= vLines; i++) {
        const lineX = x + i * step;
        ctx.moveTo(lineX, y);
        ctx.lineTo(lineX, y + height);
      }
    }

    ctx.stroke();

    // 绘制坐标轴
    ctx.beginPath();
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
    ctx.lineWidth = 1;

    // Y轴
    ctx.moveTo(x, y);
    ctx.lineTo(x, y + height);

    // X轴
    ctx.moveTo(x, y + height);
    ctx.lineTo(x + width, y + height);

    ctx.stroke();
  };

  // 绘制昨收价参考线
  const drawPreCloseLine = (ctx, x, y, width, height, preClose, minPrice, priceRange) => {
    const preCloseY = y + height - ((preClose - minPrice) / priceRange) * height;
    
    ctx.beginPath();
    ctx.strokeStyle = '#808080';
    ctx.setLineDash([4, 4]); // 设置虚线样式
    ctx.lineWidth = 1;
    
    ctx.moveTo(x, preCloseY);
    ctx.lineTo(x + width, preCloseY);
    
    ctx.stroke();
    ctx.setLineDash([]); // 恢复实线样式
  };

  // 绘制Y轴价格标签
  const drawYAxisLabels = (ctx, x, y, height, minValue, maxValue, count) => {
    ctx.fillStyle = '#b8b8b8';
    ctx.font = '12px Arial';
    ctx.textAlign = 'right';
    ctx.textBaseline = 'middle';

    const step = height / count;
    const valueStep = (maxValue - minValue) / count;

    for (let i = 0; i <= count; i++) {
      const labelY = y + height - i * step;
      const value = minValue + i * valueStep;
      ctx.fillText(value.toFixed(2), x - 10, labelY);
    }
  };

  // 绘制右侧涨跌幅标签
  const drawPercentLabels = (ctx, x, y, height, minPercent, maxPercent, count) => {
    ctx.fillStyle = '#b8b8b8';
    ctx.font = '12px Arial';
    ctx.textAlign = 'left';
    ctx.textBaseline = 'middle';

    const step = height / count;
    const valueStep = (maxPercent - minPercent) / count;

    for (let i = 0; i <= count; i++) {
      const labelY = y + height - i * step;
      const value = Number(minPercent) + i * valueStep;
      const text = value > 0 ? `+${value.toFixed(2)}%` : `${value.toFixed(2)}%`;
      ctx.fillText(text, x + 10, labelY);
    }
  };

  // 绘制成交量Y轴标签
  const drawVolumeYAxisLabels = (ctx, x, y, height, maxVolume, count) => {
    ctx.fillStyle = '#b8b8b8';
    ctx.font = '12px Arial';
    ctx.textAlign = 'right';
    ctx.textBaseline = 'middle';

    const step = height / count;
    const valueStep = maxVolume / count;

    for (let i = 0; i <= count; i++) {
      const labelY = y + height - i * step;
      const value = i * valueStep;
      ctx.fillText((value / 10000).toFixed(0) + '万', x - 10, labelY);
    }
  };

  // 绘制X轴时间标签
  const drawXAxisLabels = (ctx, x, y, width, times) => {
    if (!times || times.length === 0) return;

    ctx.fillStyle = '#b8b8b8';
    ctx.font = '12px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'top';

    const timeCount = times.length;
    // isFiveDay已经从组件参数中解构
    
    if (isFiveDay) {
      // 5日分时图 - 显示每天的开盘和收盘时间
      const days = [];
      const dayMap = {};
      
      // 按天分组
      times.forEach((time, index) => {
        const date = time.split(' ')[0]; // 提取日期部分
        if (!dayMap[date]) {
          dayMap[date] = [];
        }
        dayMap[date].push({time, index});
      });
      
      // 对每天取开盘和收盘时间
      Object.keys(dayMap).forEach(date => {
        const dayData = dayMap[date];
        if (dayData.length > 0) {
          days.push(dayData[0]); // 开盘时间
          days.push(dayData[dayData.length - 1]); // 收盘时间
        }
      });
      
      // 绘制标签
      days.forEach(item => {
        const labelX = x + (item.index / (timeCount - 1)) * width;
        ctx.fillText(item.time, labelX, y + 10);
      });
    } else {
      // 普通分时图 - 显示部分时间点
      const step = Math.max(1, Math.floor(timeCount / 5));
      
      for (let i = 0; i < timeCount; i += step) {
        const labelX = x + (i / (timeCount - 1)) * width;
        ctx.fillText(times[i], labelX, y + 10);
      }
      
      // 确保最后一个时间点显示
      if (step > 1 && (timeCount - 1) % step !== 0) {
        const labelX = x + width;
        ctx.fillText(times[timeCount - 1], labelX, y + 10);
      }
    }
  };

  // 绘制价格线
  const drawPriceLine = (ctx, x, y, width, height, prices, minPrice, priceRange) => {
    if (!prices || prices.length === 0) return;

    const preClose = data.preClose || prices[0];
    const lastPrice = prices[prices.length - 1];
    const isUp = lastPrice >= preClose;

    ctx.beginPath();
    ctx.strokeStyle = '#ffffff';
    ctx.lineWidth = 2;

    const priceCount = prices.length;
    const preCloseY = y + height - ((preClose - minPrice) / priceRange) * height;

    for (let i = 0; i < priceCount; i++) {
      const pointX = x + (i / (priceCount - 1)) * width;
      const pointY = y + height - ((prices[i] - minPrice) / priceRange) * height;

      if (i === 0) {
        ctx.moveTo(pointX, pointY);
      } else {
        ctx.lineTo(pointX, pointY);
      }
    }

    ctx.stroke();

    // 添加渐变填充
    ctx.lineTo(x + width, y + height);
    ctx.lineTo(x, y + height);
    ctx.closePath();

    const gradient = ctx.createLinearGradient(0, y, 0, y + height);
    
    // 根据价格与昨收价的关系决定填充颜色
    if (isUp) {
      // 上涨用红色
      gradient.addColorStop(0, 'rgba(246, 70, 93, 0.3)');
      gradient.addColorStop(1, 'rgba(246, 70, 93, 0.05)');
    } else {
      // 下跌用绿色
      gradient.addColorStop(0, 'rgba(14, 203, 129, 0.3)');
      gradient.addColorStop(1, 'rgba(14, 203, 129, 0.05)');
    }

    ctx.fillStyle = gradient;
    ctx.fill();
  };

  // 绘制均线
  const drawAverageLine = (ctx, x, y, width, height, avgData, minPrice, priceRange, color) => {
    if (!avgData || avgData.length === 0) return;

    ctx.beginPath();
    ctx.strokeStyle = color;
    ctx.lineWidth = 1;

    const dataCount = avgData.length;

    for (let i = 0; i < dataCount; i++) {
      const pointX = x + (i / (dataCount - 1)) * width;
      const pointY = y + height - ((avgData[i] - minPrice) / priceRange) * height;

      if (i === 0) {
        ctx.moveTo(pointX, pointY);
      } else {
        ctx.lineTo(pointX, pointY);
      }
    }

    ctx.stroke();
  };

  // 绘制成交量柱状图
  const drawVolumeChart = (ctx, x, y, width, height, volumes, maxVolume, prices) => {
    if (!volumes || volumes.length === 0) return;

    const volumeCount = volumes.length;
    const barWidth = width / volumeCount - 1;
    const preClose = data.preClose || prices[0];

    for (let i = 0; i < volumeCount; i++) {
      const barHeight = (volumes[i] / maxVolume) * height;
      const barX = x + (i / (volumeCount - 1)) * width - barWidth / 2;
      const barY = y + height - barHeight;

      // 根据价格变化决定颜色
      const isUp = i > 0 ? prices[i] >= prices[i-1] : prices[i] >= preClose;
      
      // 使用更鲜明的颜色
      ctx.fillStyle = isUp ? 'rgba(246, 70, 93, 0.8)' : 'rgba(14, 203, 129, 0.8)';

      ctx.fillRect(barX, barY, barWidth, barHeight);
    }
  };

  // 绘制图例
  const drawLegend = (ctx, x, y) => {
    const legendItems = [
      { color: '#ffffff', label: '分时' },
      { color: '#ffb100', label: '成交均价' }
    ];

    ctx.font = '12px Arial';
    ctx.textBaseline = 'middle';

    let currentX = x;

    legendItems.forEach(item => {
      // 绘制颜色方块
      ctx.fillStyle = item.color;
      ctx.fillRect(currentX, y, 12, 12);

      // 绘制标签
      ctx.fillStyle = '#e6e6e6';
      ctx.textAlign = 'left';
      ctx.fillText(item.label, currentX + 16, y + 6);

      currentX += ctx.measureText(item.label).width + 30;
    });
  };

  // 绘制十字线和数据标签
  const drawCrosshair = (ctx, width, height) => {
    if (!mousePosition) return;
    
    const { x, y } = mousePosition;
    const { padding, priceChartHeight, volumeChartHeight, volumeChartTop, chartWidth, minPrice, maxPrice, priceRange, maxVolume } = chartInfoRef.current;
    
    // 确保鼠标在图表区域内
    if (x < padding.left || x > padding.left + chartWidth || 
        y < padding.top || y > height - padding.bottom) {
      return;
    }
    
    // 获取处理后的数据数组
    let timeArray, priceArray, volumeArray, preClose;
    if (Array.isArray(data.data)) {
      // 处理第二种数据结构
      timeArray = data.data.map(item => item.time);
      priceArray = data.data.map(item => item.price);
      volumeArray = data.data.map(item => item.vol);
      preClose = data.preClose || priceArray[0];
    } else {
      // 处理第一种数据结构
      timeArray = data.time || [];
      priceArray = data.price || [];
      volumeArray = data.volume || [];
      preClose = data.preClose || priceArray[0];
    }
    
    // 计算数据点索引
    const dataCount = timeArray.length;
    const pointIndex = Math.min(
      Math.floor(((x - padding.left) / chartWidth) * dataCount),
      dataCount - 1
    );
    
    // 获取对应的数据
    const time = timeArray[pointIndex];
    const price = priceArray[pointIndex];
    const volume = volumeArray ? volumeArray[pointIndex] : 0;
    const changePercent = ((price - preClose) / preClose * 100).toFixed(2);
    const change = (price - preClose).toFixed(2);
    
    // 绘制十字线
    ctx.beginPath();
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)';
    ctx.lineWidth = 1;
    ctx.setLineDash([4, 4]); // 设置虚线样式
    
    // 垂直线
    ctx.moveTo(x, padding.top);
    ctx.lineTo(x, height - padding.bottom);
    
    // 水平线 - 价格区域
    if (y >= padding.top && y <= padding.top + priceChartHeight) {
      ctx.moveTo(padding.left, y);
      ctx.lineTo(padding.left + chartWidth, y);
    }
    
    // 水平线 - 成交量区域
    if (y >= volumeChartTop && y <= volumeChartTop + volumeChartHeight) {
      ctx.moveTo(padding.left, y);
      ctx.lineTo(padding.left + chartWidth, y);
    }
    
    ctx.stroke();
    ctx.setLineDash([]); // 恢复实线样式
    
    // 绘制数据标签
    // 价格标签 - 左侧
    const priceY = padding.top + priceChartHeight - ((price - minPrice) / priceRange) * priceChartHeight;
    ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
    ctx.fillRect(padding.left - 60, priceY - 10, 50, 20);
    ctx.fillStyle = price >= preClose ? '#f6465d' : '#0ecb81';
    ctx.font = '12px Arial';
    ctx.textAlign = 'right';
    ctx.textBaseline = 'middle';
    ctx.fillText(price.toFixed(2), padding.left - 15, priceY);
    
    // 涨跌幅标签 - 右侧
    ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
    ctx.fillRect(padding.left + chartWidth + 10, priceY - 10, 60, 20);
    ctx.fillStyle = changePercent >= 0 ? '#f6465d' : '#0ecb81';
    ctx.textAlign = 'left';
    ctx.fillText((changePercent >= 0 ? '+' : '') + changePercent + '%', padding.left + chartWidth + 15, priceY);
    
    // 时间标签 - 底部
    ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
    ctx.fillRect(x - 30, height - padding.bottom + 5, 60, 20);
    ctx.fillStyle = '#ffffff';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'top';
    ctx.fillText(time, x, height - padding.bottom + 10);
    
    // 成交量标签 - 在量柱上
    if (data.volume && y >= volumeChartTop) {
      const volumeY = volumeChartTop + 10;
      ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
      ctx.fillRect(x - 40, volumeY - 10, 80, 20);
      ctx.fillStyle = '#ffffff';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText((volume / 10000).toFixed(2) + '万手', x, volumeY);
    }
  };

  return (
    <div className="timeline-chart-container">
      <canvas 
        ref={canvasRef} 
        width={800} 
        height={height} 
        style={{ width: '100%', height: height }}
        onMouseMove={handleMouseMove}
        onMouseLeave={handleMouseLeave}
      />
    </div>
  );
};

export default TimelineChart;